package com.syswin.lhztest.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 模拟Redis客户端
 *
 * @author:lhz
 * @date:2018/12/1 16:49
 */
public class RedisClient {

	OutputStream outputStream;
	InputStream inputStream;

	//1客户端和服务器通过Tcp网络连接
	public RedisClient(String host ,int port) throws IOException {
	//建立Java客户端和Redis服务器的连接
		Socket socket = new Socket(host, port);
		//往外写数据
		outputStream = socket.getOutputStream();
		//读取服务器端返回的数据
		inputStream = socket.getInputStream();

	}

	//set key value
	public void set(String key, String value) throws IOException {
		StringBuffer data = new StringBuffer();
		//遵循协议 传输格式
		//	*3
//	$3
//	SET
//	$11
//	luohongzhou
//	$13
//"luohongzhou"
		data.append("*3").append("\r\n");

		data.append("$3").append("\r\n");
		data.append("SET").append("\r\n");

		data.append("$").append(key.getBytes().length).append("\r\n");
		data.append(key).append("\r\n");
		data.append("$").append(value.getBytes().length).append("\r\n");
		data.append(value).append("\r\n");

		//2.把指令数据发给Redis服务器
	outputStream.write(data.toString().getBytes());
		System.out.println("发送数据:" + new String(data));

		//3.接收服务器响应
		byte[] response = new byte[1024];
		inputStream.read(response);
		System.out.println("接收到响应:" + new String(response));
	}

	//get
	public String get(String key) throws IOException {
		//1.组装数据
		StringBuffer data = new StringBuffer();
		data.append("*2").append("\r\n");

		data.append("$3").append("\r\n");
		data.append("GET").append("\r\n");

		data.append("$").append(key.getBytes().length).append("\r\n");
		data.append(key).append("\r\n");
		//2.把指令数据发给Redis服务器
		outputStream.write(data.toString().getBytes());
		System.out.println("发送数据:" + new String(data));

		//3.接收服务器响应
		byte[] response = new byte[1024];
		inputStream.read(response);
		System.out.println("接收到响应:" + new String(response));
		return new String(response);
	}

	public static void main(String[] args) throws IOException {
		 RedisClient redisClient = new RedisClient("127.0.0.1",6379);
		 redisClient.set("111","1121");
		 redisClient.get("111");
	}
}
